import '../stylesheets/register.css'
import {default as contract} from 'truffle-contract'
import create_users from '../../build/contracts/CreateUsers.json';
var  User = contract(create_users);
User.setProvider(web3.currentProvider);
var NodeRSA = require("node-rsa");
window.InfNumber=0;

//当前选中的接受信息的用户，将通过getV函数进行赋值
window.receiver = "";
window.addNote=function () {
    var from_addr = getCookie('address');
    if (receiver !=""){
        User.deployed().then( async function(i) {
            var test=document.getElementById('noteInput').value;
            var text = test;
            var publickey = await getpublickey(receiver);
            /*消息加密start*/
            test = encryptPubic(publickey,test);
            /*消息加密end*/
            console.log(receiver)
            i.addNote1(test,receiver,
                {from: from_addr,
                    gas: 5000000//消息变长，消耗gas
                }
            ).then(
                function(f) {
                    var inf = text;
                    var li  = document.createElement('li');
                    li.setAttribute('id','liAdd'+InfNumber);
                    li.setAttribute('class','inf li_right');
                    li.innerText = inf;
                    li.style.cssText = "float:right;margin-right: 80px;color: black;";
                    document.getElementById('ul').appendChild(li);
                    InfNumber++;

                    /*通过localstorage存储用户发送的信息*/
                    var data = {
                        use1_add:from_addr,//当前用户
                        dt0: text,
                        dt1: test,
                        use2_rec:receiver,
                    }

                    storageInf(data)
                    //清除输入框text;
                    document.getElementById("noteInput").value ="";
                }
            )
        });

    }else {
        alert("请选择接受者！！")
    }
};


window.getNotesLen =function () {
    var from_addr = document.getElementById('text').innerText;
    User.deployed().then(function (i) {
        i.getNotesLen(from_addr).then(function (f) {
            document.getElementById('text2').innerText=f;
        })

    })
};
//get notesHistory
window.getNotesHistory =function () {
    var from_addr = document.getElementById('text').innerText;
    User.deployed().then(function (i) {
        i.getNote(from_addr,{
            from: from_addr,
        }).then(function (f) {
            i.returnotes().then(function (g) {
                let strArray = notesStringToArray(g);
                console.log(strArray);
                for (let i = 0; i<strArray.length; i++){
                    var h4 = document.createElement('h4');
                    h4.innerText = strArray[i];
                    document.getElementById('notes').appendChild(h4);

                }
                document.getElementById("notesHistory").innerText = g;

            })
        })

    })
};

//cookie存储简单数据
function setCookie(name,value,time)
{
    var strsec = getsec(time);
    var exp = new Date();
    exp.setTime(exp.getTime() + strsec*1);
    document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString();
}
function getsec(str)
{
    var str1=str.substring(1,str.length)*1;
    var str2=str.substring(0,1);
    if (str2=="s")
    {
        return str1*1000;
    }
    else if (str2=="h")
    {
        return str1*60*60*1000;
    }
    else if (str2=="d")
    {
        return str1*24*60*60*1000;
    }
}
//获得当前地址信息；
function getCookie(name)
{
    var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");

    if(arr=document.cookie.match(reg))

        return unescape(arr[2]);
    else
        return null;
}

function getGender(){
    var allRadio= null;
    var radio = document.getElementsByName("userGender");
    for ( var i=0; i<radio.length; i++){
        if (radio[i].checked){
            if(radio[i].value == 0){
                allRadio = '男';
            }else {
                allRadio = '女';
            }
        }
    }
    return allRadio
};


//add account添加账号信息
window.submitAccout = function () {
    var from_addr = getCookie('address');
    var account = document.getElementById('userAccount').value;
    var gender = getGender();
    var password = document.getElementById('userPassword').value;
    var id = document.getElementById('userId').value;
    User.deployed().then(function (i) {
        i.isInccount(from_addr).then(function (f) {
            if(f==true){
                alert("Account is exit!!!");
            }else {
                i.addAccount(account, gender, password,id,{
                        from:from_addr,
                        gas: 500000
                    }
                ).then(function(f){
                    alert("add Success!!!");
                    window.location ="chat.html";
                });
            }
        })

    });
};


window.getAccount = function () {
    var from_addr = getCookie('address');
    console.log(from_addr)
        User.deployed().then(function (i) {
            i.getAccountByAddress.call(from_addr).then(function(f){
                document.getElementById('accountName').innerText = '账 号：'+f[3];
                document.getElementById('accountId').textContent="账户id："+f[2];
            });
        });
};


//获得的聊天记录中字符床的处理??????
function notesStringToArray(notesStr) {
    notesStr += '^';
    var notesArray = new Array();
    var str="";
    var j = 0;
    var i = 0;
    console.log(notesStr.length)
    for (i=1; i < notesStr.length; i++){
        if (notesStr[i] != '^'){
            str += notesStr[i];
            console.log(str)
        }else if (notesStr[i] =='^'){
            notesArray[j] = str;
            str = "";
            j++;
        }
    }
    return notesArray;

};


//获取全部事件event//获取历史消息防止信息收到的不及时
window.getEvent = function () {
    var historyInf ={
        'sender':'',
        'time':'',
        'notes':'',
        'receiver':''
    }
    var event;//获得历史消息，也就是为了离线接收
    var sender;
    var notes;
    //var receiver = receiver;
    var number;
    User.deployed().then( function (i) {
        i.getPastEvents('NewNote', {fromBlock: 0, toBlock: 'latest'}).then( async (data) => {
            event = data;
            // console.log("event:",event)
            // console.log('信息长度：',event.length)
            number = event.length;
            sender = getCookie("address");
            for (var j=0; j< event.length;j++){
                if (receiver == event[j]['args'][2]){
                historyInf['sender'] = sender;
                notes = event[j]['args'][1];
                notes = getText(notes);
                //获取当前区块时间戳
                var t = await getTime(event[j]['blockNumber']);
                var time = timestampToTime(t['timestamp']);
                historyInf['time'] = time;
                historyInf['notes'] = notes;
                historyInf['receiver'] = event[j]['args'][0];
                // console.log('historyInf:',historyInf)
                //历史信息添加
                var li  = document.createElement('li');
                li.setAttribute('id','liAdd'+InfNumber);
                li.setAttribute('class','inf li_right');
                li.innerText = historyInf['notes'];
                li.style.cssText = "float:right;margin-right: 80px;color: #0AD5C1;";
                var div = document.createElement("div")
                div.style.cssText = "color:red";
                div.style.fontSize ='5px';//调整字体大小
                div.innerText = historyInf['time'];
                li.appendChild(div);
                document.getElementById('ul').appendChild(li);
                InfNumber++;
                }else {
                    historyInf['sender'] = sender;
                    notes = event[j]['args'][1];
                    //解密对方发来的信息
                    notes = decryptprivate(privatekey,notes);
                    //获取当前区块时间戳
                    var t = await getTime(event[j]['blockNumber']);
                    var time = timestampToTime(t['timestamp']);
                    historyInf['time'] = time;
                    historyInf['notes'] = notes;
                    historyInf['receiver'] = event[j]['args'][0];
                    // console.log('historyInf:',historyInf)
                    //历史信息添加
                    var li  = document.createElement('li');
                    li.setAttribute('id','liAdd'+InfNumber);
                    li.setAttribute('class','inf li_left');
                    li.innerText = historyInf['notes'];
                    li.style.cssText = "float:left;margin-left: 80px;color: #0AD5C1;";
                    var div = document.createElement("div")
                    div.style.cssText = "color:red";
                    div.style.fontSize ='5px';//调整字体大小
                    div.innerText = historyInf['time'];
                    li.appendChild(div);
                    document.getElementById('ul').appendChild(li);
                    InfNumber++;
                }

            }
            //删除历史记录按钮
            var gE = document.getElementById('getEvent');
            gE.style.cssText = "display:none"
        });
        // web3.eth.getAccounts(function (err, result) {
        //     console.log('web3.getaccount:',result[0])
        // })
    });

};


var dt1_dt0 ={
    dt1:""
}
//获取当前用户的历史信息 返回密文信息
function getCurrInf(k) {
    if(!window.localStorage){
        alert("浏览器支持localstorage");
    }else {
        var storage = window.localStorage;
        var js = storage.getItem(k);
        var str = JSON.parse(js)
        dt1_dt0['dt1'] = str['dt0']
        return str['dt1']
    }
}
function getText(message) {
    for (let i = 0;i<data_num;i++){
        if (message == getCurrInf("data"+i)){
            return dt1_dt0['dt1'];
        }
    }
    return "没有历史数据"
}


function getTime(number){
    return new Promise(async (resolve,reject)=>{
        await web3.eth.getBlock(number,(err,res)=>{
            resolve(res);
        });

    })
}
//add friend 添加好友
window.addFriend = function () {
    var from_addr = getCookie('address');
    var friendAdd = prompt("Please input yout friend address Or name :");
    User.deployed().then(function (i) {
        i.isInccount(friendAdd).then(function (f){
            if(f==true){
                i.addFriend(friendAdd,{
                    from:from_addr,
                    gas:500000
                }).then(function (f) {
                    alert("add success")
                });

                i.getAccountByAddress.call(friendAdd).then(function(f){
                    var imgUrl2 = require('../img/dog.png');
                    var li = document.createElement("li");
                    li.setAttribute("class","person");
                    li.setAttribute("data-chat","person2");
                    li.setAttribute("value",friendAdd);
                    li.setAttribute("onclick","getV(this);chatClick(this);cleanInf()")
                    var div = document.createElement("div");
                    div.id ="p2_img";
                    div.style.cssText ="width: 40px;height: 40px;float: left;";
                    var div2 = document.createElement("div")
                    var span = document.createElement("span")
                    span.setAttribute("class","name")
                    span.innerText = f[3];
                    var span2 = document.createElement("span");
                    span2.setAttribute("class","time");
                    //获取最后一次信息内容
                    span2.innerText = "";
                    var span3 = document.createElement("span");
                    span3.setAttribute("class","preview");
                    //获取最近一次信息时间戳
                    span3.innerText = "";
                    div2.appendChild(span);
                    div2.appendChild(span2);
                    div2.appendChild(span3);
                    li.appendChild(div);
                    li.appendChild(div2);
                    document.getElementById("p").appendChild(li);
                    addImg("p2_img", imgUrl2);
                });
            }else {
                alert("Please let's your friend jion us")

            }
        });

    });
};

//通过当前用户获得所有好友
window.researchFriends = function () {
    web3.eth.getAccounts(function (err, result) {
        console.log('web3.getaccount:',result[0])
        var res = result[0];
    console.log(res)
    User.deployed().then(function (i) {
        i.getFriendAddress.call(res).then(function (f) {
            console.log(f)
        });
    });
    });
};

//通过对方钱包地址进行查询
//时间戳转换成时间。
window.timestampToTime = function(timestamp) {
    var date = new Date(timestamp * 1000);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
    var Y = date.getFullYear() + '-';
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    var D = date.getDate() + ' ';
    var h = date.getHours() + ':';
    var m = date.getMinutes();
    if (m<10){
        m = '0'+m + ':';
    }else {
        m = date.getMinutes() + ':';
    }
    var s = date.getSeconds();
    return Y + M + D + h + m + s;
}


//获取当前发送者
var allPerson = document.getElementsByClassName('person')
window.getV = async function(element) {
  receiver = element.getAttribute("value");
    var number = await getAllfriendValue();
    var name = allPerson.valueOf()[number].children[1].children[0].textContent;
    document.getElementById('name').textContent = name;
    //将name添加到聊天框上头结束
};
async function getAllfriendValue() {
    //将name添加到聊天框上头
    return new Promise((res,rej)=>{
        var number;
        for(let i=0;i<allPerson.length;i++){
            var p = allPerson[i].getAttribute('value');
            if(receiver==p){
                number = i;
                res(number)
                break;
            }
        }

    })

}

//获取接收者的公钥
function getpublickey(receiver) {
    console.log('receive',receiver)
    return new Promise((res,rej)=>{
        User.deployed().then(i=>{
            //获取接受信息人的公钥；
            i.getPublickey(receiver).then((f)=>{
                if (f){
                    res(f)
                }else{
                    console.log('密钥不存在')
                }
            })
        })
    })
};

//公钥加密
function encryptPubic(publickey, message) {
    //公钥加密
    publickey = new NodeRSA(publickey);
    publickey.setOptions({encryptionScheme: 'pkcs1'})
    var encryData = publickey.encrypt(message,'base64','utf8');
    console.log('\n 公钥加密后的数据：\n', encryData); //加密后数据为 base64 编码
    return encryData;
};


/*本都存储localstorage json数据*/
var data_num = 0;
function storageInf(data) {
    if(!window.localStorage){
        alert("浏览器支持localstorage");
    }else{
        var storage=window.localStorage;
        var data=JSON.stringify(data);
        var k = "data"+data_num;
        storage.setItem(k,data);
        console.log("存储成功")
        // console.log(storage.getItem(k));
        //将JSON字符串转换成为JSON对象输出
        // var js=storage.getItem(k);
        // console.log(js.parse)
    }
    data_num++;
}








